package com.example.myapplication.utils

import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.text.isNullOrEmpty
import kotlin.toString


object IPUtils {
    private var ip: String? = null

    fun getPublicIPAddress(): String {
        if (!ip.isNullOrEmpty()) return ip!!

        val apiEndpoints = arrayOf<String?>(
            "https://api64.ipify.org",
            "https://icanhazip.com",
            "https://ifconfig.me/ip"
        )

        for (endpoint in apiEndpoints) {
            try {
                val url = URL(endpoint)
                val connection = url.openConnection() as HttpURLConnection
                connection.setConnectTimeout(5000)
                val reader = BufferedReader(InputStreamReader(connection.getInputStream()))
                ip = reader.readLine()
                reader.close()
                return ip.toString()
            } catch (e: Exception) {
                System.err.println("Failed to fetch IP from " + endpoint + ": " + e.message)
            }
        }
        return "111.0.238.231"
    }
}